import { HttpException, HttpStatus, Injectable } from "@nestjs/common";
import { CreateBannerDataDto, CreateBannerDto } from "./dto/create-banner.dto";
import { UpdateBannerDataDto, UpdateBannerDto } from "./dto/update-banner.dto";
import { InjectEntityManager, InjectRepository } from "@nestjs/typeorm";
import { BannerType } from "./entities/banner_type.entity";
import { EntityManager, Repository } from "typeorm";
import { BannerData } from "./entities/banner_data.entity";
import { FindBannerDataDTO, FindBannerDTO } from "./dto/find-banner.dto";
import { DeleteIds } from "../dto/all-dto";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class BannerService {
  constructor(
    @InjectRepository(BannerType)
    private bannerTypeRepository: Repository<BannerType>,
    @InjectRepository(BannerData)
    private bannerDataRepository: Repository<BannerData>,
    @InjectEntityManager()
    private entityManager: EntityManager
  ) {}

  async create(createBannerDto: CreateBannerDto) {
    const { name, code, remake } = createBannerDto;
    if (
      await this.bannerTypeRepository.createQueryBuilder().where("name = :name", { name }).getOne()
    ) throw new HttpException("名称已存在", HttpStatus.INTERNAL_SERVER_ERROR);

    if (
      await this.bannerTypeRepository.createQueryBuilder().where("code = :code", { code }).getOne()
    ) throw new HttpException("key已存在", HttpStatus.INTERNAL_SERVER_ERROR);

    const { identifiers } = await this.bannerTypeRepository.createQueryBuilder().insert().values({
      name,
      code,
      ...(remake && { remake })
    }).execute();

    if (identifiers.length === 0) {
      throw new HttpException("新增失败", HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return identifiers[0];
  }

  async findAll(findBanner: FindBannerDTO) {
    const {name,code,page,pageSize} = findBanner;
    const bannerTypeBuilder = this.bannerTypeRepository.createQueryBuilder()
    if(name){
      bannerTypeBuilder.andWhere("name LIKE :name", { name: `%${name}%` })
    }
    if(code){
      bannerTypeBuilder.andWhere("code = :code", { code })
    }
    const [list,total] = await bannerTypeBuilder.orderBy("id","DESC").skip((page-1 )* pageSize).take(pageSize).getManyAndCount()
    return {
      list,
      total
    }
  }

  findOne(id: number) {
    return `This action returns a #${id} banner`;
  }

  async update(updateBannerDto: UpdateBannerDto) {
    const {name,remake,id} = updateBannerDto;
    const {affected} = await this.bannerTypeRepository.createQueryBuilder().update().set({
      name,
      remake
    }).where("id = :id", { id }).execute()

    if(affected===0){
      throw new HttpException("修改失败", HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return ""
  }

  async  remove(deleteIds:DeleteIds) {
     let list = await this.bannerDataRepository.createQueryBuilder("bannerData")
       .leftJoinAndSelect("bannerData.bannerType","bannerType")
       .where("bannerType.id IN (:...ids)",{ids:deleteIds.ids})
       .select("bannerData.id")
       .getMany()

      let itemIds = list.map(item => item.id)

    console.log(itemIds);

      const {affected} = await this.entityManager.transaction( async transactionalEntityManager =>{
        const dataDel = await transactionalEntityManager.createQueryBuilder().delete().from(BannerData).whereInIds(itemIds).execute()
        return await transactionalEntityManager.createQueryBuilder().delete().from(BannerType).whereInIds(deleteIds.ids).execute()
      })

      if(affected===0){
        throw new HttpException("删除失败",HttpStatus.INTERNAL_SERVER_ERROR)
      }
      return "删除成功"
  }
}

export class BannerDataService {
  constructor(
    @InjectRepository(BannerType)
    private bannerTypeRepository: Repository<BannerType>,
    @InjectRepository(BannerData)
    private bannerDataRepository: Repository<BannerData>,
    private configService: ConfigService
  ) {}

  async findAll(findDataBanner: FindBannerDataDTO){

    const {code} = findDataBanner;

    const list = await this.bannerDataRepository.createQueryBuilder("bannerData")
      .leftJoin("bannerData.bannerType","bannerType")
      .where("bannerType.code = :code",{code})
      .getMany()
    list.forEach((item)=>{
      item.file = `${this.configService.get<string>("FILE_IMAGES")}${item.file}`;
    })
    return list
  }

  async create(createBannerDataDto: CreateBannerDataDto){
    const { sort,title,type,file, url,code } = createBannerDataDto;

    let newSort:number = 0;
    if(sort){
      newSort = sort;
    }else{
      newSort = await this.bannerDataRepository.createQueryBuilder("bannerData").leftJoin("bannerData.bannerType","bannerType").where("bannerType.code = :code",{code}).getCount()
    }
    const {identifiers} = await this.bannerDataRepository.createQueryBuilder().insert().values({
      sort:newSort,
      ...(title && { title : title } ),
      type,
      file,
      ...(url && { url : url }),
      bannerType: await this.bannerTypeRepository.createQueryBuilder().where("code = :code",{code}).getOne()
    }).execute()
    if(identifiers.length === 0) {
      throw new HttpException("添加失败",HttpStatus.INTERNAL_SERVER_ERROR)
    }
    return identifiers[0]
  }

  async update(updateBannerDataDto: UpdateBannerDataDto){
     const {sort, title,type,file,url, code,id} = updateBannerDataDto;
     const {affected} = await this.bannerDataRepository.createQueryBuilder().update().set({
       ...(sort && { sort} ),
       ...(title && { title }),
       ...(type && { type }),
       ...(file && {file}),
       ...(url && { url}),
     }).where("id = :id",{id}).execute()
    if(affected===0){
      throw new HttpException("更新失败", HttpStatus.INTERNAL_SERVER_ERROR)
    }
    return "ok"
  }

  async delete(deleteIds:DeleteIds){
    await this.bannerDataRepository.createQueryBuilder().delete().whereInIds(deleteIds.ids).execute()
  }
}

